#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : SIM7600CE-REST
@File    : validation_error.py
@Author  : Mr.Cai
@Date    : 2024/01/22 21:00
"""
from fastapi import Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from app.types import response
from app import config
from fastapi.encoders import jsonable_encoder


async def validationExceptionHandler(request: Request, exc: RequestValidationError):
    """ 自定义参数验证异常错误"""
    err_msg = ""
    for error in exc.errors():
        field_name = ".".join(error.get("loc"))
        err_type = error.get("type")
        if err_type in config.validateChineseDict:
            # 在定义错误模版中，并翻译出内容
            translate_msg = translate(field_name, err_type, error.get("ctx")) + "; "
            if translate_msg:
                err_msg += translate_msg
        else:
            # 不在定义模型，显示原始错误
            err_msg += ".".join(error.get("loc")) + "[" + error.get("type") + "]:" + error.get("msg") + "; "

    # 替换body.
    err_msg = err_msg.replace("body.", "")
    # 返回
    return JSONResponse(status_code=status.HTTP_200_OK, content=jsonable_encoder(response.ResponseFail(err_msg)))


def translate(fieldName: str, errType: str, limitDict: dict) -> str:
    """ 翻译错误信息"""
    # 先判断是否满足关键词错误
    for k, v in config.keyErrorChineseDict.items():
        if fieldName.find(k) != -1:
            return v

    limitValList = limitDict.values()
    try:
        return config.validateChineseDict.get(errType).format(fieldName, *limitValList)
    except Exception as e:
        return ""
